package com.example.myapplication.view.toolbar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.myapplication.R;
import com.example.myapplication.databinding.AtyCoordinatorBinding;
import com.example.myapplication.decoration.StickHeaderDecoration;

public class CoordinatorActivity extends FragmentActivity {
    private AtyCoordinatorBinding mBinding;
    private int mAppBarHeight;
    private int mBarPinHeight;

    public static void start(Context context) {
        context.startActivity(new Intent(context, CoordinatorActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.aty_coordinator);
        mBinding.setLifecycleOwner(this);

        initView();
        setListener();
    }

    protected void initView() {
        ItemAdapter adapter = new ItemAdapter(this);
        for (int i = 0; i < 100; i++) {
            adapter.add("item " + i);
        }
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.setAdapter(adapter);
        mBinding.rcv.addItemDecoration(new StickHeaderDecoration(mBinding.rcv));

        mBinding.scrollableSpace.post(() -> {
            if (mBinding != null && !isFinishing()) {
                mAppBarHeight = mBinding.scrollableSpace.getHeight();
                mBarPinHeight = mBinding.collapsedPinToolbar.getHeight();
            }
        });
    }

    private float alpha; // 不透明度 0-1  默认1不透明

    protected void setListener() {
        mBinding.appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            Log.i("Coordinator", "total height: " + mAppBarHeight + " mBarPinHeight " + mBarPinHeight
                    + " \ncurrent offset: " + verticalOffset);
            if (mAppBarHeight == 0 || mBarPinHeight == 0) return;
            int absOffsetValue = Math.abs(verticalOffset);
            if (absOffsetValue >= mAppBarHeight - 2 * mBarPinHeight) {
                int offset = mAppBarHeight - mBarPinHeight - absOffsetValue;
                float curAlpha = 1 - offset / (float) mBarPinHeight;
                if (alpha != curAlpha) {
                    alpha = curAlpha;
                    mBinding.collapsedPinToolbar.setAlpha(curAlpha);
                }
                mBinding.collapsedPinToolbar.setVisibility(View.VISIBLE);
            } else {
                mBinding.collapsedPinToolbar.setVisibility(View.INVISIBLE);
            }
        });
    }
}
